﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using TransformerManager.WPF.Common.Utils;
using hc = HandyControl.Controls;

namespace TransformerManager.WPF.OptionItemModule.ViewModels
{
    public class OptionItemDialogViewModel : BindableBase, IDialogAware
    {
        public OptionItemDialogViewModel()
        {
            InitCmd();
        }

        #region Command的定义

        public DelegateCommand YesCmd { set; get; }

        public DelegateCommand NoCmd { set; get; }

        public DelegateCommand DeleteElemCmd { set; get; }

        public DelegateCommand AddCmd { set; get; }

        public DelegateCommand UpCmd { set; get; }

        public DelegateCommand DownCmd { set; get; }

        #endregion

        public string Title => "选项编辑";

        public event Action<IDialogResult> RequestClose;

        private ObservableCollection<OptionItemObject> optionItemObjects
            = new ObservableCollection<OptionItemObject>();
        public ObservableCollection<OptionItemObject> OptionItemObjects
        {
            set
            {
                optionItemObjects = value;
                RaisePropertyChanged();
            }
            get
            {
                return optionItemObjects;
            }
        }

        private OptionItemObject selectedItem
            = new OptionItemObject();
        public OptionItemObject SelectedItem
        {
            get
            {
                return selectedItem;
            }
            set
            {
                selectedItem = value;
                RaisePropertyChanged();
            }
        }

        private OptionItemObject addedItem
            = new OptionItemObject();
        public OptionItemObject AddedItem
        {
            get
            {
                return addedItem;
            }
            set
            {
                addedItem = value;
                RaisePropertyChanged();
            }
        }

        private string xmlFileName = string.Empty;
        public string XmlFileName
        {
            get
            {
                return xmlFileName;
            }
            set
            {
                xmlFileName = value;
                RaisePropertyChanged();
            }
        }

        private string elementName = string.Empty;
        public string ElementName
        {
            get
            {
                return elementName;
            }
            set
            {
                elementName = value;
                RaisePropertyChanged();
            }
        }

        #region 函数的定义

        private void InitCmd()
        {
            YesCmd = new DelegateCommand(() =>
            {
                var result = hc.MessageBox.Show(
                    "是否保存编辑?",
                    "保存?",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question);
                if(result == MessageBoxResult.Yes)
                {
                    OnDialogClosed();
                }
            });

            NoCmd = new DelegateCommand(() =>
            {
                RequestClose?.Invoke(new DialogResult(ButtonResult.No));
            });

            DeleteElemCmd = new DelegateCommand(() =>
            {
                if (selectedItem == null) return;

                bool isSuccess = OptionItemObjects.Remove(selectedItem);

                if(!isSuccess)
                {
                    hc.Growl.Error($"响应信息：错误!删除操作失败!", "Notification");
                }
            });

            AddCmd = new DelegateCommand(() => {
                if (addedItem == null) return;

                var item = OptionItemObjects
                    .FirstOrDefault(o => 
                    o.ENName.Trim() == addedItem.ENName.Trim()
                        || o.CNName.Trim() == addedItem.CNName.Trim());
                
                if(item == null)
                {
                    OptionItemObjects.Add(addedItem);
                    AddedItem = new OptionItemObject();
                }
                else
                {
                    hc.Growl.Error($"响应信息：错误!{addedItem.CNName}|" +
                        $"{addedItem.ENName}已存在!", "Notification");
                    AddedItem.CNName = string.Empty;
                    AddedItem.ENName = string.Empty;
                    RaisePropertyChanged(nameof(AddedItem));
                }
            });

            UpCmd = new DelegateCommand(()=>
            {
                if (selectedItem == null) return;

                int index = optionItemObjects.IndexOf(selectedItem);
                int count = optionItemObjects.Count;
                // 当选中项移动至表格顶端，或者表格中只有小于等于一项内容，则不进行任何操作
                if (count <= 1 || index == 0) return; 

                int updateIndex = index - 1;
                int removeIndex = index + 1;
                updateIndex = updateIndex < 0 ? 0 : updateIndex;
                removeIndex = removeIndex > count ? count : removeIndex;

                OptionItemObjects.Insert(updateIndex, selectedItem);
                OptionItemObjects.RemoveAt(removeIndex);
                SelectedItem = OptionItemObjects[updateIndex];
            });

            DownCmd = new DelegateCommand(()=> 
            {
                if (selectedItem == null) return;

                int index = optionItemObjects.IndexOf(selectedItem);
                int count = optionItemObjects.Count;
                // 当选中项移动至表格最底部，或者表格中只有小于等于一项内容，则不进行任何操作
                if (count <= 1 || index == count - 1) return; 

                int updateIndex = index + 2; // 获取移动后对象的索引号
                int removeIndex = index;
                updateIndex = updateIndex > count ? (count - 1) : updateIndex;

                OptionItemObjects.Insert(updateIndex, selectedItem);
                OptionItemObjects.RemoveAt(removeIndex);
                SelectedItem = OptionItemObjects[updateIndex - 1];
            });
        }

        #endregion


        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            DialogParameters dialogParams = new DialogParameters()
            {
                { "UpdatedOptItems", optionItemObjects}
            };
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK, dialogParams));
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            var dialogInParams = parameters
                .GetValue<ObservableCollection<OptionItemObject>>("OptionItemObjects");
            if (dialogInParams != null)
            {
                OptionItemObjects = dialogInParams;
            }

            XmlFileName = parameters.GetValue<string>("xmlFileName");
            ElementName = parameters.GetValue<string>("elementName");
        }
    }
}
